﻿using FunArts.EasyDevOps.Rcl.Service;
using FunArts.EasyDevOps.Shared.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Pickers;
using WinRT.Interop;

namespace FunArts.EasyDevOps.Platforms.Windows.Service.Impl
{
    /// <summary>
    /// 应用程序windows平台读取文件实现
    /// </summary>
    public class LocalFileService: ILocalFileService
    {
        public static nint windowHandle => WindowNative.GetWindowHandle(App.Current.Windows[0].Handler.PlatformView as MauiWinUIWindow);

        public async Task<KeyValuePair<string, byte[]>> OpenFile(string fileName = "")
        {
            if (!fileName.IsNullOrWhiteSpace())
            {
                Stream stream=File.OpenRead(fileName);
                using var memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                return new KeyValuePair<string, byte[]>(fileName, memoryStream.ToArray());
            }
            var fileResult = await FilePicker.Default.PickAsync();
            if (fileResult != null)
            {
                using var stream = await fileResult.OpenReadAsync();
                using var memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                return new KeyValuePair<string, byte[]>(fileResult.FileName, memoryStream.ToArray());
            }
            return new KeyValuePair<string, byte[]>();
        }

        public async Task<KeyValuePair<string, List<string>>> OpenDir()
        {
            var folderPicker = new FolderPicker();
            folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
            folderPicker.FileTypeFilter.Add("*");

            InitializeWithWindow.Initialize(folderPicker, windowHandle);

            var folder = await folderPicker.PickSingleFolderAsync();
            if (folder != null)
            {
                if (Directory.Exists(folder.Path))
                {
                    var allFiles = await GetAllFilesAsync(folder.Path);
                    return new KeyValuePair<string, List<string>>(folder.Path, allFiles);
                }
            }
            return new KeyValuePair<string, List<string>>();
        }

        private async Task<List<string>> GetAllFilesAsync(string folderPath, string searchPattern = "*")
        {
            var files = new List<string>();

            try
            {
                files.AddRange(await Task.Run(() => Directory.GetFiles(folderPath, searchPattern)));
                foreach (var subDir in await Task.Run(() => Directory.GetDirectories(folderPath)))
                {
                    files.AddRange(await GetAllFilesAsync(subDir, searchPattern));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"读取文件路径出错:{folderPath}: {ex.Message}");
            }

            return files;
        }
    }
}
